/** 
 * 题目：插入函数调用参数
 * 将：console.log(1);
 * 转换为：console.log('文件名（行号，列号）：', 1);
 * 地址：https://juejin.cn/book/6946117847848321055/section/6945997926376144899
 */
const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const generate = require("@babel/generator").default;
const types = require("@babel/types");

// 源码
const sourceCode = `
    console.log(1);

    function func() {
        console.info(2);
    }

    export default class Clazz {
        say() {
            console.debug(3);
        }
        render() {
            return <div>{console.error(4)}</div>
        }
    }
`;

// 步骤一：解析生成AST
const ast = parser.parse(sourceCode, {
  sourceType: 'unambiguous',
  plugins: ['jsx'],
})

// 步骤二：遍历AST
traverse(ast, {
  CallExpression(path, state) {
    if (
      types.isMemberExpression(path.node.callee) &&
      path.node.callee.object.name === "console" &&
      ["log", "info", "error", "debug"].includes(path.node.callee.property.name)
    ) {
      const { line, column } = path.node.loc.start;
      path.node.arguments.unshift(types.stringLiteral(`filename:(${line}, ${column})`))
    }
  }
})

// 步骤三：生成
const { code, map } = generate(ast);
console.log(code);

/**
console.log("filename:(2, 4)", 1);

function func() {
  console.info("filename:(5, 8)", 2);
}

export default class Clazz {
  say() {
    console.debug("filename:(10, 12)", 3);
  }

  render() {
    return <div>{console.error("filename:(13, 25)", 4)}</div>;
  }

}

*/

